package com.bgs.controller;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bgs.pojo.Money;
import com.bgs.service.MoneyService;
import com.bgs.tool.R;
import com.bgs.utils.LocaldatetimeUtils;
import com.bgs.vo.MoneyVo;
import com.bgs.vo.SocialDetailsVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailSendException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 工资表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-05-08
 */
@CrossOrigin
@RestController
@RequestMapping("/money")
@Slf4j
public class MoneyController {
    @Autowired
    private MoneyService moneyService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @ApiOperation(value = "登录用户的所有工资列表")
    @GetMapping("/findAllMoney/{eid}")
    public R findAllMoney(@ApiParam(name = "eid", value = "用户id", required = true)
                              @PathVariable String eid){
        List<Money> list = moneyService.list(new QueryWrapper<Money>().eq("userid",eid));
        List<MoneyVo> mlist = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            MoneyVo m = new MoneyVo();
            BeanUtils.copyProperties(list.get(i),m);
            m.setTime(LocaldatetimeUtils.timess(list.get(i).getPaytime())+"工资表");
            m.setShifa(m.getBasic()+m.getOverpay()-m.getDeduction());
            mlist.add(m);
        }
        return R.ok().data("list",mlist);
    }

    //根据工资ID进行查询
    @ApiOperation(value = "根据ID值查询工资")
    @GetMapping("/getIdMoney/{id}")
    public R getIdMoney(
            @ApiParam(name = "id", value = "工资ID", required = true)
            @PathVariable String id){
        Money m = moneyService.getById(id);
            return R.ok().data("Money",m);
    }

    @ApiOperation(value = "修改工资（需要有ID值）")
    @PostMapping("/updateMoney")
    public R updateMoney(@RequestBody MoneyVo m){

        boolean flag = moneyService.updateMoney(m);
        if (flag){
            return R.ok();
        }else {
            return R.error();
        }
    }

    @ApiOperation(value = "所有工资列表")
    @PostMapping("/findAll")
    public R findAll(@RequestBody(required = false) MoneyVo m){
        log.info("模糊查询前端传过来的数据MoneyVo"+m);
        PageHelper.startPage(m.getPage(),m.getLimit());
        List<MoneyVo> list = moneyService.listAll(m);
        for (int i = 0; i < list.size(); i++) {
            BeanUtils.copyProperties(list.get(i),m);
            list.get(i).setTime(LocaldatetimeUtils.timess(list.get(i).getPaytime())+"工资条");
            list.get(i).setShifa(m.getBasic()+m.getOverpay()-m.getDeduction());
        }
        PageInfo<MoneyVo> pageInfo = new PageInfo<MoneyVo>(list);
        return  R.ok().data("total",pageInfo.getTotal()).data("rows",pageInfo.getList());
    }


    @ApiOperation(value = "修改工资（需要有ID值）")
    @PostMapping("/addMoney")
    public R addMoney(@RequestBody MoneyVo m){

        boolean flag = moneyService.addMoney(m);
        if (flag){
            return R.ok();
        }else {
            return R.error();
        }
    }

    @Value("${mail.fromMail.sender}")
    private String sender;// 发送者

    @Autowired
    private JavaMailSender javaMailSender;

    @PostMapping("/sendEmail")
    public R sendEmail(@RequestBody MoneyVo m) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sender);
        message.setTo(m.getEmployee().getEmail());
        message.setSubject("OA");// 标题
        message.setText("【OA】"+m.getEmployee().getName()+"您的工资条已发送，请及时确认状态，" +
                "24小时候系统会自动帮你确认的！(若不是本人操作，可忽略该条邮件)");// 内容
        try {
            javaMailSender.send(message);
            log.info("文本邮件发送成功！");
            return R.ok();
        }catch (MailSendException e){
            log.error("目标邮箱不存在");
            return R.error();
        } catch (Exception e) {
            log.error("文本邮件发送异常！", e);
            return R.error();
        }
    }

    @ApiOperation(value = "删除工资（需要有ID值）")
    @PostMapping("/delMoney/{id}")
    public R delMoney( @PathVariable Integer id){
        boolean flag = moneyService.deleteByPrimaryKey(id);
        if (flag){
            return R.ok();
        }else {
            return R.error();
        }
    }

}

